package tools

import (
	"github.com/zeromicro/go-zero/core/logx"
	"net"
	"strings"
)

func getInterface() (map[string]string, error) {
	ips := make(map[string]string)
	interfaces, err := net.Interfaces()
	if err != nil {
		return nil, err
	}
	for _, i := range interfaces {
		byName, err := net.InterfaceByName(i.Name)
		if err != nil {
			return nil, err
		}
		addresses, _ := byName.Addrs()
		for _, v := range addresses {
			ip := strings.Split(v.String(), "/")[0]
			cip := net.ParseIP(ip).To4()
			if cip != nil && !cip.IsLoopback() {
				ips[ip] = i.HardwareAddr.String() + " " + byName.Name // 打印网卡byName.Name
			}
		}
	}
	return ips, nil
}

func GetActiveIP() (ip, mac string) {
	conn, err := net.Dial("udp", "1.1.1.1:53")
	if err == nil {
		defer func(conn net.Conn) {
			err := conn.Close()
			if err != nil {
				logx.Error(err)
			}
		}(conn)
		ip = strings.Split(conn.LocalAddr().String(), ":")[0]
	}
	ipMap, err := getInterface()
	if err != nil {
		return
	}
	mac = ipMap[ip]
	return
}
